
/**
** \file       redirection.c
**
** \brief      this function parse the redirection rule
**
** \author     Ben M'rad Hanna, Laterem Hamza, Boillot Ulysse, De Olivera
**             Guillaume and Nguyen Viet Dung
**
** \version    0.8
**
** \date       26 November 2010
**
*/

#include "rules.h"

static s_redir          *rule_redirection1(char                 *str,
                                           s_redir              *redir)
{
  if (g_data->lexer == NULL)
    return (NULL);

  if (strcmp(g_data->lexer->token->id, str) != 0)
    return (NULL);

  redir->type = malloc(sizeof (char) * strlen(str));
  redir->type = strcpy(redir->type, str);

  g_data->lexer = g_data->lexer->next;

  if (g_data->lexer == NULL)
  {
    free(redir->type);
    return (NULL);
  }

  if (g_data->lexer->token->type != TOKEN_WORD)
    return (NULL);

  redir->string = malloc(sizeof (char) * strlen(g_data->lexer->token->id));
  redir->string = strcpy(redir->string, g_data->lexer->token->id);

  g_data->lexer = g_data->lexer->next;

  return (redir);
}

static s_redir          *rule_redirection2(char                 *str,
                                           s_redir              *redir)
{
  if (g_data->lexer == NULL)
    return (NULL);

  if (strcmp(g_data->lexer->token->id, str) != 0)
    return (NULL);

  redir->type = malloc(sizeof (char) * strlen(str));
  redir->type = strcpy(redir->type, str);
  g_data->lexer = g_data->lexer->next;

  if (g_data->lexer == NULL)
  {
    free(redir->type);
    return (NULL);
  }

  if (g_data->lexer->token->type != TOKEN_DLESSDASH)
    return (NULL);

  redir->string = malloc(sizeof (char) * strlen(g_data->lexer->token->id));
  redir->string = strcpy(redir->string, g_data->lexer->token->id);
  g_data->lexer = g_data->lexer->next;

  return (redir);
}

static s_redir          *my_init2(s_redir                       *redir)
{
  redir->nb_io = -1;
  redir->type = NULL;
  redir->string = NULL;

  if ((g_data->lexer->token->type == TOKEN_IONUMBER))
  {
    redir->nb_io = atoi(g_data->lexer->token->id);
    g_data->lexer = g_data->lexer->next;
  }
  return (redir);
}

s_redir                 *rule_redirection(s_redir               *redir)
{
  if (g_data->lexer == NULL)
    return (NULL);

  redir = my_init2(redir);

  if (rule_redirection1(">", redir) != NULL)
    return (redir);

  if (rule_redirection1("<", redir) != NULL)
    return (redir);

  if (rule_redirection1(">>", redir) != NULL)
    return (redir);

  if (rule_redirection2("<<", redir) != NULL)
    return (redir);

  if (rule_redirection2("<<-", redir) != NULL)
    return (redir);

  if (rule_redirection1(">&", redir) != NULL)
    return (redir);

  if (rule_redirection1("<&", redir) != NULL)
    return (redir);

  if (rule_redirection1(">|", redir) != NULL)
    return (redir);

  if (rule_redirection1("<>", redir) != NULL)
    return (redir);

  return (NULL);
}
